import { isArray } from "lodash"
import { ValidationError } from 'class-validator'

export const NotFound = {
    code: -32602,
    message: 'not found'
}

export const InvalidToken = {
    code: -32602,
    message: 'invalid token symbol'
}

export function BadRequest(message: string) {
    return {
        code: -32602,
        message: message
    }
}

export function BadRequest2(errors: ValidationError[]) {
    const constraints = errors[0].constraints
    if (!constraints) {
        return {
            code: -32602,
            message: 'bad request'
        }
    }

    return {
        code: -32602,
        message: constraints[Object.keys(constraints)[0]]
    }
}

/**
 * 生成模型数据
 * @param model - Model
 * @param params - 参数列表
 */
 export function makeModel<T>(model: T, params: any) {
    const obj = model as any
    const keys = Object.keys(obj)

    if (!isArray(params)) {
        keys.forEach((key) => {
            obj[key] = params[key]
        })
        return model
    }

    keys.forEach((key, index) => {
        if (index < params.length) {
            obj[key] = params[index]
        }
    })
    return model
}

/**
 * 数组转换Object，将两个数组合约返回
 * @param keys - Object key 列表
 * @param values - Object value 列表
 */
export function arrayToObject(keys: string[], values: any[]) {
    let obj = Object.create(null)
    for (let idx = 0; idx < values.length; idx++) {
        if (idx >= keys.length) {
            break
        }
        obj[keys[idx]] = values[idx]
    }
    return obj
}
